<?php

namespace App\Services\Admin\Order;

use App\Exceptions\OrderException;
use App\Helpers\MvcHelper;
use App\Models\Admin\User\UserUpdateOrderRecordsModel;
use App\Models\Applet\Order\ShopOrderExpressModel;
use App\Models\Applet\Order\ShopOrderModel;
use Exception;
use Illuminate\Support\Facades\DB;

class ShopOrderService extends BaseOrderService
{

    /**
     * 商品订单列表
     * @param array $params
     * @return array[]
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getShopOrderModel()->total($params);

        // 查询商品订单列表
        $shopOrderList = $this->getShopOrderModel()->list($params, [
            'shop_orders.id', 'shop_orders.order_master_id', 'shop_orders.goods_id', 'shop_orders.order_no',
            'shop_orders.total_price', 'shop_orders.order_price', 'shop_orders.order_integral', 'shop_orders.quantity',
            'shop_orders.order_status', 'shop_orders.remark', 'nickname', 'phone', 'shop_master_orders.order_no as order_master_no',
            'pay_type', 'pay_status', 'pay_time', 'shop_master_orders.remark'
        ]);

        // 查询商品主订单列表
        $masterOrderIds = array_column($shopOrderList, 'order_master_id');

        // 查询快递信息
        $orderExpressList = $this->getShopOrderExpressModel()->getItemByOrderMasterIds($masterOrderIds, [
            'id', 'order_master_id', 'express_no', 'status', 'remark'
        ]);
        $orderExpressListMap = array_column($orderExpressList, null, 'order_master_id');

        $list = [];
        foreach ($shopOrderList as $item) {
            $orderExpress = null;
            if (isset($orderExpressListMap[$item['order_master_id']])) {
                $orderExpress = [
                    'expressNo' => $orderExpressListMap[$item['order_master_id']]['express_no'] ?? '',
                    'status' => $orderExpressListMap[$item['order_master_id']]['status'] ?? '',
                    'remark' => $orderExpressListMap[$item['order_master_id']]['remark'] ?? ''
                ];
            }

            $list[] = [
                'id' => $item['id'],
                'userName' => $item['nickname'] ?? '',
                'phone' => $item['phone'] ?? '',
                'masterOrderNo' => $item['order_master_no'],
                'orderNo' => $item['order_no'],
                'totalPrice' => $item['order_price'],
                'orderPrice' => $item['order_price'],
                'totalIntegral' => $item['order_integral'],
                'quantity' => $item['quantity'],
                'orderStatus' => $item['order_status'],
                'payType' => $item['pay_type'],
                'payStatus' => $item['pay_status'],
                'payTime' => $item['pay_time'] ?? '',
                'remark' => $item['remark'],
                'orderExpress' => $orderExpress,
            ];
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 商品订单详情
     * @param array $params
     * @return array
     * @throws OrderException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 商品订单详情
        $orderDetail = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'goods_id', 'order_no', 'total_price', 'order_price', 'order_integral', 'quantity', 'order_status', 'remark'
        ]);
        if (empty($orderDetail)) {
            throw new OrderException('商品订单不存在', OrderException::CODE_2001);
        }

        // 查询商品主订单详情
        $masterOrderDetail = $this->getShopMasterOrderModel()->getItemById($orderDetail['order_master_id'], [
            'id', 'user_id', 'order_no', 'pay_type', 'pay_status', 'pay_time', 'remark'
        ]);

        // 查询用户列表
        $userInfo = $this->getUserModel()->getItemById($masterOrderDetail['user_id'], [
            'id', 'nickname', 'phone'
        ]);


        // 查询订单商品
        $orderGoods = $this->getShopOrderGoodsModel()->getItemByOrderIdAndGoodsId($orderDetail['id'], $orderDetail['goods_id'], [
            'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'params'
        ]);

        // 查询类型
        $categoryDetail = $this->getShopCategoryModel()->getItemById($orderGoods['category_id'], [
            'id', 'title', 'img_url'
        ]);

        // 查询地区
        $areaIds = [$orderGoods['province_id'], $orderGoods['city_id'], $orderGoods['region_id']];
        $areaListData = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaList = [];
        foreach ($areaListData as $item) {
            $areaList[] = [
                'id' => $item['code'],
                'name' => $item['name'],
            ];
        }

        // 查询收货地址
        $orderAddress = $this->getShopOrderAddressModel()->getItemByOrderMasterId($masterOrderDetail['id'], [
            'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id'
        ]);

        // 查询地区
        $addressAreaIds = [$orderAddress['province_id'], $orderAddress['city_id'], $orderAddress['region_id']];
        $addressAreaList = $this->getAreaModel()->getAreaNameListByCodeList($addressAreaIds);
        $addressNameList = array_column($addressAreaList, 'name');
        $addressAreaName = $this->getAreaName(...$addressNameList);

        // 查询快递信息
        $orderExpress = $this->getShopOrderExpressModel()->getItemByOrderMasterId($masterOrderDetail['id'], [
            'id', 'express_no', 'phone', 'status', 'remark'
        ]);

        $expressInfo = [];
        if (!empty($expressInfoData)) {
            $expressList = $this->getExpressApi()->query($expressInfoData['express_company_code'], $expressInfoData['express_no'], $expressInfoData['phone']);
            // 更新物流状态
            $this->getShopOrderExpressModel()->updateItemById($expressInfoData['id'], [
                'status' => ShopOrderExpressModel::STATUS_DELIVERY,
            ]);

            $expressInfo = [
                'expressNo' => $expressInfoData['express_no'],
                'list' => $expressList
            ];
        }

        return [
            'id' => $orderDetail['id'],
            'orderMasterNo' => $masterOrderDetail['order_no'],
            'orderNo' => $orderDetail['order_no'],
            'totalPrice' => $orderDetail['total_price'] / 100,
            'orderPrice' => $orderDetail['total_price'] / 100,
            'totalIntegral' => $orderDetail['total_price'] / 100,
            'quantity' => $orderDetail['quantity'],
            'orderStatus' => $orderDetail['order_status'],
            'payType' => $masterOrderDetail['pay_type'],
            'payStatus' => $masterOrderDetail['pay_status'],
            'payTime' => $masterOrderDetail['pay_time'] ?? '',
            'remark' => $orderDetail['remark'],
            'userInfo' => [
                'id' => $userInfo['id'],
                'nickname' => $userInfo['nickname'],
                'phone' => $userInfo['phone'],
            ],
            'categoryInfo' => $categoryDetail,
            'areaList' => $areaList,
            'addressInfo' => [
                'receiveName' => $orderAddress['receive_name'],
                'receiveTel' => $orderAddress['receive_tel'],
                'areaInfo' => $orderAddress['area_info'],
                'address' => $orderAddress['address'],
                'areaName' => $addressAreaName,
            ],
            'orderExpress' => [
                'expressNo' => $orderExpress['express_no'] ?? '',
                'status' => $orderExpress['status'] ?? '',
                'remark' => $orderExpress['remark'] ?? ''
            ],
            'orderGoods' => $orderGoods,
            'expressInfo' => $expressInfo,
        ];
    }

    /**
     * 操作发货
     * @return void
     * @throws Exception
     */
    public function delivery(array $params)
    {
        // 商品订单详情
        $orderDetail = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id'
        ]);
        if (empty($orderDetail)) {
            throw new OrderException('商品订单不存在', OrderException::CODE_2001);
        }

        $createOrderExpressData = [
            'order_master_id' => $orderDetail['order_master_id'],
            'express_company_code' => $params['expressCompanyCode'],
            'express_no' => $params['expressNo'] ?? '',
            'phone' => $params['phone'] ?? '',
            'status' => ShopOrderExpressModel::STATUS_WAIT_DELIVERY,
        ];

        DB::transaction(function () use ($orderDetail, $createOrderExpressData) {
            // 更新订单状态
            $this->getShopOrderModel()->updateItemById($orderDetail['id'], [
                'order_status' => ShopOrderModel::ORDER_STATUS_DELIVERY,
            ]);

            // 添加订单快递
            $this->getShopOrderExpressModel()->addItem($createOrderExpressData);
        });
    }

    /**
     * 更新订单状态
     * @return void
     * @throws OrderException
     * @throws Exception
     */
    public function update(array $params)
    {
        $shopOrder = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'order_status'
        ]);
        if (empty($shopOrder)) {
            throw new OrderException('商品订单不存在', OrderException::CODE_2001);
        }

        if ($shopOrder['order_status'] != ShopOrderModel::ORDER_STATUS_WAIT) {
            throw new OrderException('状态不允许操作', OrderException::CODE_1002);
        }

        DB::transaction(function () use ($params, $shopOrder) {
            // 更新订单状态
            $this->getShopOrderModel()->updateItemById($params['id'], [
                'order_status' => $params['orderStatus']
            ]);
            // 添加订单手动操作记录
            $this->getUserUpdateOrderRecordsModel()->addItem([
                'type' => UserUpdateOrderRecordsModel::TYPE_SHOP_ORDER,
                'admin_user_id' => MvcHelper::getLoginUserId(),
                'order_id' => $params['id'],
                'old_order_status' => $shopOrder['order_status'],
                'new_order_status' => $params['orderStatus'],
                'remark' => $params['remark'],
            ]);
        });
    }
}
